import React, { useState, memo, forwardRef, useImperativeHandle } from 'react'
import { Modal, Tree } from 'antd';
import type { DataNode } from 'antd/es/tree';
import { setRigthsUser } from '../../../api/roles';
function SetRights(props: any, ref: any) {
    let [isOpen, setOpen] = useState(false);
    let [roleId,setroleId] = useState<number>(0)
    //定义展开指定得节点树状态
    let [expandedKeys,setExpandedKeys] = useState<number[]>([]);
    // 当前选中复选框节点状态列表
    let [checkedKeys,setCheckedKeys] = useState<number[]>([]);
    // 树形数据
    let [treeData,setTreeData] = useState<DataNode[]>([]);
    // 定义半选中得key
    let [halfCheckedKeys,setHalfCheckedKeys] = useState<number[]>([]);
    let onOk =async () => {
        // 获取办选中和全选中得id;
        let keys:number[] = [...checkedKeys,...halfCheckedKeys];
        let rids:string = keys.join(",");
        console.log(rids);
        let res = await setRigthsUser(roleId,rids);
        if(res.data.meta.status === 200){
            console.log(res)
            cancelHandler();
            props.over();
        }
    }
    let cancelHandler = () => {
        setOpen(false)
    }
    let init = (treeList:any,rigtsList:RolesChildrenItem[],id:number) => {
        //rigtsList 表示当前角色得权限列表
        // treeList 表示当前所有得权限列表
        setroleId(id)
        // 处理数据 将当前角色得一级权限id 二级权限id 存放到expandedKeys 三级权限id存放到checkedKeys;
        let expandeds:number[] =[];
        let checkeds:number[] = [];
        rigtsList.forEach((item:RolesChildrenItem)=>{
            // 一级权限
            expandeds.push(item.id);
            item.children?.map((item2:RolesChildrenItem)=>{
                // 二级权限
                expandeds.push(item2.id)
                item2.children?.map((item3:RolesChildrenItem)=>{
                    //三级
                    checkeds.push(item3.id)
                })
            })
        })
        setCheckedKeys(checkeds);
        setExpandedKeys(expandeds);
        setTreeData(treeList)
        setOpen(true)
    }
    useImperativeHandle(ref, () => {
        return {
            init
        }
    })
    // 展开收起节点时触发事件
    let onExpand = (expandedKeys:any)=>{
        setExpandedKeys(expandedKeys)
    }
    // 点击复选框时触发
    let onCheck = (checkedKeys:any,e:any)=>{
        setCheckedKeys(checkedKeys);
        setHalfCheckedKeys(e.halfCheckedKeys)
    }
    return (
        <Modal title="分配权限" open={isOpen} onOk={onOk} onCancel={cancelHandler} okText='确定' cancelText='取消'>
            <Tree
                checkable
                onExpand={onExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={false}
                onCheck={onCheck}
                checkedKeys={checkedKeys}
                fieldNames={{
                    title:"authName",
                    key:"id",
                }}
                treeData={treeData}
            />
        </Modal>
    )
}

export default memo(forwardRef(SetRights))
